package com.kly.smartbi.controller.oj;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kly.smartbi.annotation.AuthCheck;
import com.kly.smartbi.common.*;
import com.kly.smartbi.constant.UserConstant;
import com.kly.smartbi.exception.BusinessException;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.model.dto.question.QuestionAddRequest;
import com.kly.smartbi.model.dto.question.QuestionEditRequest;
import com.kly.smartbi.model.dto.question.QuestionQueryRequest;
import com.kly.smartbi.model.dto.question.QuestionUpdateRequest;
import com.kly.smartbi.model.entity.Question;
import com.kly.smartbi.model.entity.User;
import com.kly.smartbi.model.vo.QuestionVO;
import com.kly.smartbi.service.QuestionService;
import com.kly.smartbi.service.UserService;
import com.kly.smartbi.utils.BloomFilterUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

import static com.kly.smartbi.constant.ChartRedisConstant.TEN_TIME_TTL;
import static com.kly.smartbi.constant.PostRedisConstant.POST_LOCK_DETAIL_KEY;
import static com.kly.smartbi.constant.QuestionRedisConstant.QUESTION_DETAIL_CACHE_KEY;
import static com.kly.smartbi.constant.QuestionRedisConstant.QUESTION_GET_BLOOM_NAME;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private BloomFilterUtil bloomFilterUtil;

    @Resource
    private RedissonClient redissonClient;

    private RBloomFilter<String> bloomFilter;

    Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder().maximumSize(10_000).initialCapacity(1024).expireAfterWrite(Duration.ofMinutes(TEN_TIME_TTL + RandomUtil.randomInt(1, 5))).build();

    @PostConstruct
    public void init() {
        // 在Spring Bean初始化完成后创建布隆过滤器
        this.bloomFilter = bloomFilterUtil.create(QUESTION_GET_BLOOM_NAME, 1000000, 0.001);
    }

    // region 增删改查

    /**
     * 创建
     *
     * @param questionAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = questionService.addQuestion(questionAddRequest);
        return ResultUtils.success(id);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        // List<String> tags = questionUpdateRequest.getTags();
        // if (tags != null) {
        //     question.setTags(JSONUtil.toJsonStr(tags));
        // }
        // // 参数校验
        // questionService.validQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }


    /**
     * 添加bloomFilter参数
     */
    @PostMapping("/add/bloomFilter")
    public BaseResponse<String> addBloomFilter() {
        // 添加到布隆过滤器
        questionService.lambdaQuery().list().forEach(question -> {
            bloomFilter.add(String.valueOf(question.getId()));
        });
        return ResultUtils.success("ok");
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 防止缓存雪崩 设置过期时间 随机值
        int expireTime = TEN_TIME_TTL + RandomUtil.randomInt(1, 5);
        // 判断是否为空 防止缓存穿透
        if (!bloomFilter.contains(String.valueOf(id))) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }
        // 多级缓存 caffeine redis 防止缓存雪崩
        String key = String.format("%s%s", QUESTION_DETAIL_CACHE_KEY, id);
        String questionCache = LOCAL_CACHE.getIfPresent(key);
        if (StrUtil.isNotBlank(questionCache)) {
            return ResultUtils.success(JSONUtil.toBean(questionCache, QuestionVO.class));
        }

        if ("".equals(questionCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }

        // 查询缓存判断是否存在
        questionCache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(questionCache)) {
            // 写入缓存 caffeine
            LOCAL_CACHE.put(key, questionCache);
            return ResultUtils.success(JSONUtil.toBean(questionCache, QuestionVO.class));
        }
        // 判断是否为空 防止缓存穿透
        if ("".equals(questionCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }
        String lockKey = String.format("%s%s", POST_LOCK_DETAIL_KEY, id);
        RLock lock = redissonClient.getLock(lockKey);
        QuestionVO questionVO = null;
        try {
            // 互斥锁 防止缓存击穿
            boolean tryLock = lock.tryLock(TEN_TIME_TTL, -1, TimeUnit.SECONDS);
            if (tryLock) {
                Question question = questionService.getById(id);
                if (question == null) {
                    // 写入缓存 redis caffeine
                    LOCAL_CACHE.put(key, "");
                    stringRedisTemplate.opsForValue().set(key, "", expireTime, TimeUnit.MINUTES);
                    throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
                }
                questionVO = questionService.getQuestionVO(question, request);
                // questionThumbService.setHasThumbByZSet(questionVO);
                // 写入缓存 redis caffeine
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(questionVO), expireTime, TimeUnit.MINUTES);
                LOCAL_CACHE.put(key, JSONUtil.toJsonStr(questionVO));
            }
        } catch (Exception e) {
            log.info("getQuestionById error");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        } finally {
            // 判断是否持有锁 释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return ResultUtils.success(questionVO);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size), questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();

        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size), questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size), questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        // List<String> tags = questionEditRequest.getTags();
        // if (tags != null) {
        //     question.setTags(JSONUtil.toJsonStr(tags));
        // }
        // // 参数校验
        // questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<QuestionVO>> searchQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.searchFromEs(questionQueryRequest);
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }


    // region 测试分布式缓存 springcache

    @GetMapping("/test/query")
    @ApiOperation("测试查询 cache")
    @Cacheable(value = "question:test", key = "#idRequest.id")
    public BaseResponse<Question> testQuery(IdRequest idRequest) {
        log.info("开始查询 {}", idRequest);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Question question = questionService.getById(idRequest.getId());
        return ResultUtils.success(question);
    }

    @GetMapping("/test/update")
    @ApiOperation("测试更新 cache")
    @CacheEvict(value = "question:test", key = "#questionEditRequest.id")
    public BaseResponse<Boolean> testUpdate(@RequestBody QuestionEditRequest questionEditRequest) {
        log.info("开始更新 {}", questionEditRequest);
        Question question = BeanUtil.copyProperties(questionEditRequest, Question.class);
        boolean result = questionService.updateById(question);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(true);
    }


    // end region
}
